//
//  YTFLoginViewController.m
//  weibo_yoo_OC
//
//  Created by pro on 16/2/28.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "YTFLoginViewController.h"
#import <AFNetworking.h>
#import "NSObject+Content.h"
#import "YTFUserModel.h"


typedef void(^success)();
typedef void(^failure)();
@interface YTFLoginViewController ()<UIWebViewDelegate>

//定义一个webview
@property(nonatomic,weak)UIWebView *webView;


@end

@implementation YTFLoginViewController

//把修改view的操作放在loadView中
-(void)loadView{
    
    //初始化一个webView,并赋值给主View
    UIWebView *webView = [[UIWebView alloc]init];
    
    self.webView = webView;
    
    //设置代理
    webView.delegate = self;
    
    self.view = webView;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
    //加载网页
    //获取url
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@&response_type=code",APP_KEY,APP_URL]];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    [self.webView loadRequest:request];
    
    
}


//定义一个方法来设置这个view
-(void)setupUI{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(comeBack)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"自动填充" style:UIBarButtonItemStylePlain target:self action:@selector(setupAll)];
    
}


-(void)comeBack{
    [self dismissViewControllerAnimated:YES completion:nil];
}


//使用js注入
-(void)setupAll{
    NSString *js = @"document.getElementById(\"userId\").value = \"youtengfei2009@163.com\";document.getElementById(\"passwd\").value = \"andyyou116116\";";
    [self.webView stringByEvaluatingJavaScriptFromString:js];
    
}


#pragma mark - UIWebView的代理方法
-(void)webViewDidStartLoad:(UIWebView *)webView{

}

-(void)webViewDidFinishLoad:(UIWebView *)webView{

}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{

}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
//    NSLog(@"%@",request.URL.absoluteString);
    //判断utl是否有值
    NSString *urlStr = request.URL.absoluteString;
    if (urlStr) {
        
        //判断我们需要的字符串，是以“http://www.sina.com.cn”为前缀的
        if ([urlStr hasPrefix:APP_URL]) {
//            NSLog(@"%@",urlStr);
            //第一种截取字符串的方法
           //根据指定字符串获取一个字符数组
            NSArray *array = [urlStr componentsSeparatedByString:@"="];
            
            if (array.count > 0) {
                //获取code字符串
                NSString *code = array.lastObject;
                
//                [self loadTokenWithCode:code];
                [self loadTokenWithCode:code withSuccess:^{
                    NSLog(@"success");
                } andWithFailure:^{
                    NSLog(@"failure");
                }];
                
            }
            
        }
    }
    
    
    return YES;
}


//定义一个字典转模型的方法
-(void)loadTokenWithCode:(NSString*)code withSuccess:(success)success andWithFailure:(failure)failure{
    //实例化一个管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain",nil];
    
    //设置参数
    NSDictionary *dict = @{@"client_id":APP_KEY,
                           @"client_secret":APP_SECRET,
                           @"grant_type":@"authorization_code",
                           @"code":code,
                            @"redirect_uri":APP_URL};
    
    //发送post请求
    [manager POST:@"https://api.weibo.com/oauth2/access_token" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"%@",responseObject);
        
        YTFUserModel *userModel = [[YTFUserModel alloc]initWithDict:responseObject];;
        
//        NSLog(@"%@",userModel.access_token);
        
        //获取用户信息
//        [self getUserInfoWithModel:userModel];
        [self getUserInfoWithModel:userModel withSuccess:success andWithFailure:failure];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}


//根据access_token获取用户信息
-(void)getUserInfoWithModel:(YTFUserModel*)userModel withSuccess:(success)success andWithFailure:(failure)failure{
    //创建一个管理类
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //设置参数
    NSDictionary *dict = @{
                           @"access_token":userModel.access_token,
                           @"uid":userModel.uid
                           };
    
    //发送请求
    [manager GET:@"https://api.weibo.com/2/users/show.json" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"%@",responseObject);
        
        userModel.profile_image_url = responseObject[@"profile_image_url"];
        userModel.screen_name = responseObject[@"screen_name"];
        //保存到沙盒中
        [userModel saveUserInfo];
        
        //调用成功的block
        success();
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        //调用失败的block
        failure();
    }];
    
}

@end










